<?php

namespace app\common\library;

use fast\Random;
use think\Db;
use think\Hook;
use think\Log;

/**
 * IM 升级 对应类
 */
class Ims
{
    //openIM 密钥
    protected static $secret = 'openIM@XiYan666';
    //userID APP 管理员 ID
    protected static $adminID = 'imAdmin';

    //获取管理员 token 本地使用
    protected static $get_admin_token_url = 'https://im.admin.ranxuxing.com/api/auth/get_admin_token';
    //线上
//    protected static $get_admin_token_url = '127.0.0.1:10002/auth/get_admin_token';

    //查询用户是否注册 本地使用
    protected static $account_check_url = 'https://im.admin.ranxuxing.com/api/user/account_check';
    //线上
//    protected static $account_check_url = '127.0.0.1:10002/user/account_check';

    //获取用户的 token，需指定用户登录时所使用的终端类型。   operationID 6 小程序
    protected static $user_token_url = 'https://im.admin.ranxuxing.com/api/auth/get_user_token';
    //线上
//    protected static $user_token_url = '127.0.0.1:10002/auth/get_user_token';

    //户通过 AppServer 完成账号注册后，AppServer 再调用此接口导入 IM 以实现账号打通
    protected static $user_register_url = 'https://im.admin.ranxuxing.com/api/user/user_register';
    //线上
//    protected static $user_register_url = '127.0.0.1:10002/user/user_register';


    //修改用户的头像、名称、Ex等信息。仅传需要修改的字段，也支持零值。
    protected static $update_user_info_url = 'https://im.admin.ranxuxing.com/api/user/update_user_info_ex';
    //线上
//    protected static $update_user_info_url = '127.0.0.1:10002/user/update_user_info_ex';


    //模拟身份向指定用户或群组发送消息，也可用于从其他平台导入历史记录。
    protected static $send_msg_url = 'https://im.admin.ranxuxing.com/api/msg/send_msg';
    //线上
//    protected static $send_msg_url = '127.0.0.1:10002/msg/send_msg';


    //业务服务发送自定义通知，客户端会收到OnRecvCustomBusinessMessage回调  关闭订单回调
    protected static $send_business_msg_url = 'https://im.admin.ranxuxing.com/api/msg/send_business_notification';
    /**
     * 查询用户是否注册
     * @return void
     */
    public static function account_check($userId){
        //先获取管理员 token
        $content = ['secret'=>self::$secret,'userId'=>self::$adminID];
        $data =  ims_admin_token_post(self::$get_admin_token_url,json_encode($content));
        $ret = json_decode($data,true);
        $token = '';
        $usertoken = '';
        if($ret['errCode']==0){
            $token = $ret['data']['token'];
        }
        if(!empty($token)){
            //查询用户是否注册
            $accountStatus = 0;  //账户状态，0：未注册，1：已注册
            $account_data = ims_account_check_post(self::$account_check_url,$userId,$token);
            $ret1 = json_decode($account_data,true);
            if($ret1['errCode']==0){
                $accountStatus = $ret1['data']['results'][0]['accountStatus'];
            }
            if($accountStatus==0){ //未注册 先注册在查询token
                //注册
                $postdata = [];
                $postdata['users'][] = [
                    'userID'=>strval($userId),
                    'nickname'=>Db::name('user')->where(['id'=>$userId])->value('nickname'),
                    'faceURL'=>Db::name('user')->where(['id'=>$userId])->value('avatar'),
                ];
                $registerdata = ims_user_register_post(self::$user_register_url,json_encode($postdata),$token);
                $ret3 = json_decode($registerdata,true);
                if($ret3['errCode']==0){
                    //注册成功
                }
            }
            //已注册用户，直接获取用户token 给前台
            $postdata1 = ['platformID'=>6,'userId'=>strval($userId)];
            $userdata = ims_get_user_token_post(self::$user_token_url,json_encode($postdata1),$token);
            $ret2 = json_decode($userdata,true);
            if($ret2['errCode']==0){
                $usertoken = $ret2['data']['token'];
            }
        }
        return $usertoken;
    }
    //批量注册
    public static function pilang_account_check($zxsid){
        //先获取管理员 token
        $content = ['secret'=>self::$secret,'userId'=>self::$adminID];
        $data =  ims_admin_token_post(self::$get_admin_token_url,json_encode($content));
        $ret = json_decode($data,true);
        $token = '';
        $usertoken = '';
        if($ret['errCode']==0){
            $token = $ret['data']['token'];
        }
        $user_id = $zxsid;
        $nickname = Db::name('mental_xlzxinfo')->where(['id'=>$user_id])->value('full_name');
        $faceURL = Db::name('mental_xlzxinfo')->where(['id'=>$user_id])->value('image');
        $zxsid = 'zxs'.$zxsid;
        if(!empty($token)){
            //查询用户是否注册
            $accountStatus = 0;  //账户状态，0：未注册，1：已注册
            $account_data = ims_account_check_post(self::$account_check_url,$zxsid,$token);
            $ret1 = json_decode($account_data,true);
            if($ret1['errCode']==0){
                $accountStatus = $ret1['data']['results'][0]['accountStatus'];
            }
            if($accountStatus==0){ //未注册 先注册在查询token
                //注册
                $postdata = [];
                $postdata['users'][] = [
                    'userID'=>$zxsid,
                    'nickname'=>$nickname,
                    'faceURL'=>$faceURL,
                ];
                $registerdata = ims_user_register_post(self::$user_register_url,json_encode($postdata),$token);
                $ret3 = json_decode($registerdata,true);
                if($ret3['errCode']==0){
                    //注册成功
                }
            }

        }
        return;
    }

    /**
     * 修改用户的头像、名称、Ex等信息。仅传需要修改的字段，也支持零值。
     * @param $userId
     * @return int
     */
    public static function update_user_check($userId){
        //先获取管理员 token
        $content = ['secret'=>self::$secret,'userId'=>self::$adminID];
        $data =  ims_admin_token_post(self::$get_admin_token_url,json_encode($content));
        $ret = json_decode($data,true);
        $token = '';
        $update_status = 0;
        if($ret['errCode']==0){
            $token = $ret['data']['token'];
        }
        if(!empty($token)){
            $postdata1 = [];
            $zxs = Db::name('mental_xlzxinfo')->where(['user_id'=>$userId,'status'=>1])->find();
            if(!empty($zxs)){
                $avatar = $zxs['image'];
                $nickname = $zxs['full_name'];
            }else{
                $nickname = Db::name('user')->where(['id'=>$userId])->value('nickname');
                $avatar = Db::name('user')->where(['id'=>$userId])->value('avatar');
            }
            $postdata1['userInfo'] = [
                'userID'=>strval($userId),
                'nickname'=>$nickname,
                'faceURL'=>$avatar,
                "ex"=>""
            ];
            $userdata = ims_update_user_info_post(self::$update_user_info_url,json_encode($postdata1),$token);
            $ret2 = json_decode($userdata,true);
            if($ret2['errCode']==0){
                $update_status = 1;
            }
        }
        return $update_status;
    }

    /**
     * 模拟身份向指定用户或群组发送消息，也可用于从其他平台导入历史记录。
     * @param $zxsid
     * @param $userId
     * @return true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function send_msg($zxsid,$userId){
        //先获取管理员 token
        $content = ['secret'=>self::$secret,'userId'=>self::$adminID];
        $data =  ims_admin_token_post(self::$get_admin_token_url,json_encode($content));
        $ret = json_decode($data,true);
        $token = '';
        if($ret['errCode']==0){
            $token = $ret['data']['token'];
        }
        $true = 0;
        if(!empty($token)){
            Log::info('到这里Token验证通过了');
            $zxs_id = str_replace("zxs", "", $zxsid);
            $zxsinfo = Db::name('mental_xlzxinfo')->where(['id'=>$zxs_id])->where('status',1)->find();
            if(!empty($zxsinfo['introduce'])){
                $b = [];
                $b['sendID'] = $zxsid;
                $b['recvID'] = $userId;
                $b['groupID'] = '';
                $b['senderNickname'] = $zxsinfo['full_name'];
                $b['senderFaceURL'] = $zxsinfo['image'];
                $b['senderPlatformID'] = 6;
                $b['content'] = [
                    "content"=>$zxsinfo['introduce'],
                ];
                $b['contentType'] = 101;
                $b['sessionType'] = 1;
                $b['isOnlineOnly'] = false;
                $b['notOfflinePush'] = false;
                $b['sendTime'] = round(microtime(true) * 1000);
                $b['offlinePushInfo'] = [
                    'title'=>'',
                    'desc'=>'',
                    'ex'=>'',
                    'iOSPushSound'=>"default",
                    'iOSBadgeCount'=>true,
                ];
                $b['ex'] = '';
                $userdata = ims_send_msg_post(self::$send_msg_url,json_encode($b),$token);
                $ret2 = json_decode($userdata,true);
                if($ret2['errCode']==0){
                    Log::info('到这里算是发送成功了');
                    $true = 1;
                }
            }
        }

        return $true;
    }

    /**
     * 验证token
     * @param $userId
     * @return void
     */
    public static function imtoken_check($userId,$role)
    {
        $usertoken = '';
        //先获取管理员 token
        $content = ['secret'=>self::$secret,'userId'=>self::$adminID];
        $data =  ims_admin_token_post(self::$get_admin_token_url,json_encode($content));
        $ret = json_decode($data,true);
        $token = '';
        if($ret['errCode']==0){
            $token = $ret['data']['token'];
        }
        if($role=='PSYCHOLOGIST'){
            $user_id = str_replace("zxs", "", $userId);
            $nickname = Db::name('mental_xlzxinfo')->where(['id'=>$user_id])->value('full_name');
            $faceURL = Db::name('mental_xlzxinfo')->where(['id'=>$user_id])->value('image');
        }
        if($role=='USER'){
            $nickname = Db::name('user')->where(['id'=>$userId])->value('nickname');
            $faceURL = Db::name('user')->where(['id'=>$userId])->value('avatar');
        }
        //已注册用户，直接获取用户token 给前台
        $postdata1 = ['platformID'=>6,'userId'=>$userId];
        $userdata = ims_get_user_token_post(self::$user_token_url,json_encode($postdata1),$token);
        $ret2 = json_decode($userdata,true);
        if($ret2['errCode']==0){
            $usertoken = $ret2['data']['token'];
        }else{
            //未获取到token
            //注册
            $postdata = [];
            $postdata['users'][] = [
                'userID'=>$userId,
                'nickname'=>$nickname,
                'faceURL'=>$faceURL,
            ];
            $registerdata = ims_user_register_post(self::$user_register_url,json_encode($postdata),$token);
            $ret3 = json_decode($registerdata,true);
            if($ret3['errCode']==0){
                //注册成功
            }
            $postdata5 = ['platformID'=>6,'userId'=>$userId];
            $userdata = ims_get_user_token_post(self::$user_token_url,json_encode($postdata5),$token);
            $ret5 = json_decode($userdata,true);
            if($ret5['errCode']==0){
                $usertoken = $ret5['data']['token'];
            }
        }
        return $usertoken;
    }

    /**
     * @param $orderId
     * 关闭订单，发业务通知
     */
    public static function send_business_notification($orderId)
    {
        $order = Db::name('consult_order')->where(['id'=>$orderId])->find();
        //先获取管理员 token
        $content = ['secret'=>self::$secret,'userId'=>self::$adminID];
        $data =  ims_admin_token_post(self::$get_admin_token_url,json_encode($content));
        $ret = json_decode($data,true);
        $token = '';
        if($ret['errCode']==0){
            $token = $ret['data']['token'];
        }
        Log::info('token:'.$token);
        $update_status = 0;
        if(!empty($token)){
            $postdata1 = [
                'sendUserID'=>"openIMAdmin",
                'recvUserID'=>strval($order['user_id']),
                'recvGroupID'=>"",
                "key"=>"ORDER_CLOSE",
                "data"=>$orderId,
                "sendMsg"=>false,
                "reliabilityLevel"=>1,
            ];
            $userdata = ims_send_business_post(self::$send_business_msg_url,json_encode($postdata1),$token);
            $ret2 = json_decode($userdata,true);
            Log::info('ret2:'.$ret2['errCode']);
            if($ret2['errCode']==0){
                $update_status = 1;
            }
            Log::info($update_status);
        }
        return $update_status;

    }

    /**
     * @param $orderId
     * @return int
     * 有新订单发送业务通知
     */
    public static function send_business_notification_order($orderId)
    {
        $order = Db::name('consult_order')->where(['id'=>$orderId])->find();
        //先获取管理员 token
        $content = ['secret'=>self::$secret,'userId'=>self::$adminID];
        $data =  ims_admin_token_post(self::$get_admin_token_url,json_encode($content));
        $ret = json_decode($data,true);
        $token = '';
        if($ret['errCode']==0){
            $token = $ret['data']['token'];
        }
        Log::info('下单token:'.$token);
        $update_status = 0;
        if(!empty($token)){
            $postdata1 = [
                'sendUserID'=>"openIMAdmin",
                'recvUserID'=>strval('zxs'.$order['xlzxinfo_id']),
                'recvGroupID'=>"",
                "key"=>"NEW_ORDER",
                "data"=>strval($order['user_id']),
                "sendMsg"=>false,
                "reliabilityLevel"=>1,
            ];
            $userdata = ims_send_business_post(self::$send_business_msg_url,json_encode($postdata1),$token);
            $ret2 = json_decode($userdata,true);
            Log::info('下单ret2:'.$ret2['errCode']);
            if($ret2['errCode']==0){
                $update_status = 1;
            }
            Log::info($update_status);
        }
        return $update_status;

    }

}
